package com.inspur.jzsxxzx.controller.common;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.inspur.jzsxxzx.entity.primary.CustomUserDetails;
import com.inspur.jzsxxzx.service.primary.UserService;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    /*
     * @Autowired
     * private UserService userService;
     * 
     * 
     * @GetMapping("/register")
     * public String showRegistrationForm(Model model) {
     * return "register";
     * }
     * 
     * @PostMapping("/register")
     * public String registerUser(@RequestParam String username,
     * 
     * @RequestParam String password,
     * Model model) {
     * try {
     * // 检查用户名是否已存在
     * User existingUser = userService.findByUsername(username);
     * if (existingUser != null) {
     * model.addAttribute("error", "用户名已存在");
     * return "register";
     * }
     * 
     * // 注册新用户
     * userService.registerUser(username, password);
     * // 明确重定向到登录页面
     * return "redirect:/login?registered=true";
     * } catch (Exception e) {
     * System.out.println(e);
     * model.addAttribute("error", "注册失败，请重试");
     * return "register";
     * }
     * }
     */

    @GetMapping("/login")
    public String showLoginForm(@RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout,
            @RequestParam(value = "registered", required = false) String registered,
            Model model) {
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }
        if (logout != null) {
            model.addAttribute("message", "您已成功退出登录");
        }
        if (registered != null) {
            model.addAttribute("message", "注册成功，请登录");
        }
        return "login";
    }

    @GetMapping("/change-password")
    public String showChangePasswordForm() {
        return "fragments/change-password :: changePassword";
    }

    @PostMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(Authentication authentication,
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            @RequestParam String confirmNewPassword) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 在服务端也进行密码验证
            if (newPassword.length() < 6) {
                response.put("success", false);
                response.put("error", "密码长度不能少于6位");
                return ResponseEntity.badRequest().body(response);
            }

            if (!newPassword.equals(confirmNewPassword)) {
                response.put("success", false);
                response.put("error", "新密码与确认密码不匹配");
                return ResponseEntity.badRequest().body(response);
            }

            CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
            Long userId = userDetails.getId();
            boolean success = userService.updatePassword(userId, oldPassword, newPassword);

            if (success) {
                response.put("success", true);
                response.put("message", "密码修改成功，请重新登录");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("error", "原密码错误");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "密码修改失败，请重试");
            return ResponseEntity.status(500).body(response);
        }
    }
}